import styles from "./index.module.scss";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import swagger from "@/assets/swagger.svg";
import { getListApi, deteleApi, addApi, updateApi } from "@/api/list/index";

interface List {
  contentId: any;
  content: string;
  achieve: number | boolean;
}

interface AddType {
  userId: number;
  content: string;
  achieve: number;
}

function index() {
  const [uname, setUname] = useState("游客");

  const [isShow, setIsShow] = useState(false); // 控制登录 退出功能
  const navigateTo = useNavigate();

  // 新增
  const [taskValue, setTaskValue] = useState("");
  const [list, setList] = useState<List[]>([
    // { id: 1, content: '四六级阅读理解', achieve: false },
  ]);
  useEffect(() => {
    if (localStorage.getItem("userData")) {
      let a = JSON.parse(localStorage.getItem("userData"));
      setUname(a.uname);
      setIsShow(true);
      listData();
    }
  }, []);

  // 查询
  const listData = async () => {
    let a: any = JSON.parse(localStorage.getItem("userData"));
    let res: any = await getListApi(a.userId);
    setList(res.data);
  };
  // 新增
  const addData = () => {
    let a = JSON.parse(localStorage.getItem("userData"));
    let data = {
      userId: a.userId,
      content: taskValue,
      achieve: 0,
    };
    addApi(data);
  };

  const onChange = (item) => {
    if (localStorage.getItem("userData")) {
      let a = JSON.parse(localStorage.getItem("userData"));
      let updateData = {
        contentId: item.contentId,
        userId: a.userId,
        content: item.content,
        achieve: item.achieve == 0 ? 1 : 0,
      };
      updateApi(updateData);
      // 刷新数据
      listData();
      listData();
      listData();
    } else {
      setList(() =>
        list.map((items) =>
          items.contentId == item.contentId
            ? { ...items, achieve: item.achieve == 0 ? 1 : 0 }
            : items
        )
      );
      console.log(list);
    }
  };

  const onChangeAll = (e) => {
    if (e.target.checked == true) {
      setList((arr) => arr.map((item) => ({ ...item, achieve: 1 })));
    } else {
      setList((arr) => arr.map((item) => ({ ...item, achieve: 0 })));
    }
  };

  // 删除
  const deleteItem = (item) => {
    if (localStorage.getItem("userData")) {
      // 删除数据库
      deteleApi(item.contentId);
      // 再次请求数据刷新
      listData();
      listData();
      listData();
    } else {
      setList(list.filter((current) => current.contentId !== item.contentId));
    }
  };

  // 新增
  const addItem = () => {
    if (taskValue == "") {
      window.confirm("请输入内容");
    } else {
      if (localStorage.getItem("userData")) {
        // 新增到数据库
        addData();
        // 再次请求数据刷新
        listData();
      } else {
        var uuid = new Date().getTime() + Math.random().toString(36).substr(2);
        setList([...list, { contentId: uuid, content: taskValue, achieve: 0 }]);
        setTaskValue("");
      }
    }
  };

  // 全部清除
  const clearItem = () => {
    if (window.confirm("你确定要全部清空吗？")) {
      if (localStorage.getItem("userData")) {
        // 删除数据库
        list.forEach((item) => {
          deteleApi(item.contentId);
        });
        // 再次请求数据刷新
        listData();
        listData();
      } else {
        setList([]);
      }
    }
  };
  const allList = () => {
    listData();
  };

  // 已完成
  const finished = () => {
    // setList(list.filter((current) => current.achieve == 1));
    if (localStorage.getItem("userData")) {
      setList(list.filter((current) => current.achieve == 1));
    } else {
      setList(list.filter((current) => current.achieve == 1));
    }
  };

  // 未完成
  const unfinished = () => {
    if (localStorage.getItem("userData")) {
      // 再次请求数据刷新
      //  listData();
      setList(list.filter((current) => current.achieve == 0));
    } else {
      setList(list.filter((current) => current.achieve == 0));
    }
  };

  function addTask(e) {
    if (e.keyCode === 13 && taskValue != "") {
      if (localStorage.getItem("userData")) {
        // 新增到数据库
        addData();
        setTaskValue("");
        // 再次请求数据刷新
        listData();
        listData();
      } else {
        var uuid = new Date().getTime() + Math.random().toString(36).substr(2);
        setList([...list, { contentId: uuid, content: taskValue, achieve: 0 }]);
        setTaskValue("");
      }
    }
  }

  return (
    <div className={styles.container}>
      <header>
        <h1 style={{ color: "#262626" }}>{uname}</h1>
        <div className={styles.swagger}>
          <img src={swagger} alt="" />
          <a
            href="http://43.139.99.222:8077/swagger-ui/"
            style={{ color: "#262626", marginLeft: "10px" }}
          >
            Swagger
          </a>
        </div>
        <button
          style={isShow ? { display: "none" } : null}
          onClick={() => {
            navigateTo("/login");
          }}
        >
          登录
        </button>
        <button
          style={!isShow ? { display: "none" } : null}
          onClick={() => {
            navigateTo("/login");
            localStorage.setItem("userData", "");
          }}
        >
          退出
        </button>
      </header>
      <section className={styles.main}>
        <div className={styles.card}>
          <h1 style={{ color: "#262626" }}>Todolsit</h1>
          <div className={styles.add}>
            <input
              value={taskValue}
              onKeyUp={addTask}
              onChange={(e) => setTaskValue(e.target.value)}
              placeholder="记录一下"
            />
            <button
              style={{ height: "40px" }}
              className={taskValue == "" ? styles.addbtn1 : styles.addbtn2}
              onClick={addItem}
              disabled={taskValue == ""}
            >
              添加
            </button>
          </div>
          <section className={styles.item}>
            <ul
              className={styles.todolist}
              style={{ maxHeight: "300px", overflow: "auto" }}
            >
              {list.map((item) => (
                <li key={item.contentId}>
                  <input
                    onChange={(e) => onChange(item)}
                    className={styles.toggle}
                    type="checkbox"
                    checked={item.achieve == 0 || false ? false : true}
                  />
                  <label>{item.content}</label>
                  <button
                    className={styles.delete}
                    onClick={() => deleteItem(item)}
                  ></button>
                </li>
              ))}
            </ul>
          </section>
          <footer className={styles.footer}>
            <input
              onChange={(e) => onChangeAll(e)}
              className={styles.toggle}
              type="checkbox"
            />
            <span className="todo-count">任务总数：{list.length}</span>
            <span>
              已完成：{list.filter((item) => item.achieve == 1).length}
            </span>
          </footer>
        </div>
        <section className={styles.tabbar}>
          <div onClick={clearItem}>清空</div>
          <div onClick={allList}>全部</div>
          <div onClick={finished}>已完成</div>
          <div onClick={unfinished}>未完成</div>
        </section>
      </section>
    </div>
  );
}

export default index;
